<template>
    <PageWrapper v-loading="loading" loading-tip="加载中...">
        <div class="p-4 p-4-tag">
            <div class="tag">
                <!-- 报警明细 -->
                 <div class="top">
                    <p class="container-title">报警信息</p>
                    <ul class="container-ul">
                        <li>报警编码：<span class="color-33">{{infoData.detailData.AlarmCode}}</span></li>
                        <li>报警主题：<span class="color-33">{{infoData.detailData.AlarmTopic}}</span></li>
                        <li>严重性：<span class="color-33">{{infoData.detailData.AlarmLevel_text}}</span></li>
                        <li>报警类别：<span class="color-33">{{infoData.detailData.AlarmType_text}}</span></li>
                        <li>报警状态：<span class="color-33">{{infoData.detailData.AlarmStatus_text}}</span></li>
                        <li>报警时间：<span class="color-33">{{infoData.detailData.EndTime}}</span></li>
                        <li>故障描述：<span class="color-33">{{infoData.detailData.Description}}</span></li>
                    </ul>
                 </div>
                 <!-- 多轴折线图 -->
                 <div class="center">
                    <div class="top-item">
                        <div
                            class="item"
                            v-for="(item, index) in lineChartArr"
                            :key="index"
                            :class="{ isSelected: item.isSelect }"
                            @click="handleLineFilter(item)"
                        >
                            <div
                                class="item-chunk"
                                :style="{
                                    background: `${!item.isSelect ? item.color : '#e4e5e6'}`
                                }"
                            ></div>
                            <div class="item-title">{{ item.title }}</div>
                        </div>
                    </div>
                    <policeLinechart
                            :loading="loadingByLinechart"
                            :seriesVal="seriesValByLinechart"
                            height="600px" />
                 </div>
                 <!-- 添加分组 -->
                <div class="bottom">
                    <div>
                        <a-button type="primary" @click = "addGroup"> 添加分组 </a-button>
                    </div>
                    <div class="group-item" v-for="(item,index) in infoData.groupList">
                       <div class="group-item-title">
                            <span class="container-title">
                                {{item.name }}
                                <!-- <Icon icon="ant-design:eye-filled" /> -->
                            </span>
                            <span class="group-item-btn">
                                <a-button style="margin-right: 10px;" @click="addAttribute(index)">编辑 </a-button>
                                <a-button @click="delgroup(index)"> 删除分组 </a-button>
                            </span>
                       </div>
                       <ul class="group-item-list" v-if="item.attributeList && item.attributeList.length > 0">
                            <li v-for="(litem,lindex) in item.attributeList">
                                {{litem.Name}}
                                <!-- <Icon icon="ant-design:eye-filled" class="icon-eye"/> -->
                                <CloseOutlined  class="icon-close" @click="delAttribute(item,lindex)"/>
                            </li>
                       </ul>
                    </div>
                </div>
            </div>
            <!-- 添加属性弹窗 -->
            <modelByAttribute
                class="model"
                :info="attributeForm"
                 @register="register"
                @submit-success="handleUpdateAttribute"
            />
        </div>
    </PageWrapper>
</template>

<script setup lang="ts">
import { PageWrapper } from '/@/components/Page';
import { ref, onMounted, onBeforeUnmount, reactive, nextTick } from 'vue';
import Icon from '/@/components/Icon';
import { CloseOutlined } from '@ant-design/icons-vue';
import modelByAttribute from '/@/views/project/alertRules/components/modelByAttribute.vue';
import { useModal } from '/@/components/Modal';
import policeLinechart from '/@/views/project/alertRules/components/policeLinechart.vue';
import { getalarmdiagnose, recorddiagnosis } from '/@/api/alertRules/index';
import { getObjectLocalStorage } from '/@/storage/storage';
import { Console, log } from 'console';

let loading = ref(false);
let loadingByLinechart = ref(true)
let seriesValByLinechart = reactive({
    seriesData: [] as any, //主要数据
    xAxis: [] as any, //点名称
    legend: [] as any, //标题
    legendSelected: [] as any, //控制显示隐藏
    yAxis: [] as any, //纵轴
})
let localDataByAlarmrecord = getObjectLocalStorage('localDataByAlarmrecord') || {
    _record: {}
};
console.log(localDataByAlarmrecord)
let lineChartArr = reactive([]) as any;
let weatherData = ref([] as any)
const selected = reactive<Record<string, boolean>>({});

let infoData = reactive({
    detailData: {} as any,
    AlarmCode: '',
    AlarmTopic: '',
    AlarmLevel_text: '',
    AlarmType_text: '',
    AlarmStatus_text: '',
    EndTime: '',
    Description: '',
    groupList: [] as any,
})
let selectIndex = ref(0)
//添加属性弹窗
let attributeForm = reactive({
    GroupName: '',
    data: [],
});
const [register, { openModal, closeModal }] = useModal();


//获取诊断明细
async function getDiagnosticDetails() {
    try {
        let res = await getalarmdiagnose([localDataByAlarmrecord._record.Id]);
        if(res){
            infoData.detailData = res
            if(res.Attention && res.Attention.length !==0){
                let _Attention = {
                    name:'分组1',
                    attributeList: res.Attention 
                }
                infoData.groupList.push(_Attention)
                getGroupDetail()
            }
        }
    
    } catch (error) {
        
    }
}

//处理数据格式
function queryWeather() {
    // 根据poi_code对数据进行分组
    let groupedData = {};
    //属性集合
    let groupKey = {}, groupMap = {};
    infoData.groupList.forEach(one => {
        groupMap[one.name] = {};
        one.attributeList.forEach(o => {
            groupKey[o.Name] = [];
            groupMap[one.name][o.Name] = [];
        });
    });
    console.log(groupKey,'groupKey');
    weatherData.value.forEach((item) => {
        var groupItemKey = groupMap[item.GroupName];
        // 判断当前poi_code是否存在groupedData中，以下是不存在的情况
        if (!groupedData[item.GroupName]) {
            // 不存在则创建一个新的键值对
            
            groupedData[item.GroupName] = {
                Time: [],
                ...groupItemKey,
                color:item.color,
                GroupName: item.GroupName
            };
        }
        
        groupedData[item.GroupName].Time.push(item.Time);
        Object.keys(groupItemKey).forEach(key => {
            groupedData[item.GroupName][key].push([item.Time || null, item[key]===undefined?null: item[key]]); // 处理null值
        });
    });
    console.log(groupedData, '组的数据-------');
    let echartsData = [] as any;
    for (let code in groupedData) {
        var groupItemKey = groupMap[code];
        const temp = {
            name: code,
            Time: groupedData[code].Time,
            // 电流: groupedData[code].电流,
            // 电压: groupedData[code].电压,
            // 功率: groupedData[code].功率,
            // 温度: groupedData[code].温度,
            color: groupedData[code].color,
            GroupName: groupedData[code].GroupName,
        }
        Object.keys(groupItemKey).forEach(key => {
            temp[key] = groupedData[code][key]
        })

        echartsData.push(temp);
    }
    
   
    let offsetIncrement = 30;
    let startOffset = 20;
    echartsData = echartsData.map((item, index) => ({
        ...item,
        offset: startOffset + index * offsetIncrement
    }));
    console.log(echartsData, '');
    let series = [] as any;
    let yData = [] as any;
    // 动态设置xAxis的data和series
    echartsData.forEach((data,index) => {
        var groupItemKey = groupMap[data.name];
        seriesValByLinechart.xAxis.data = data.Time; // 设置x轴的时间数据（注意：这里可能需要根据实际情况调整，因为所有组的时间可能不一致）
        data.offset = data.offset + 10;
        // 为每个poi_code创建一个series
        Object.keys(groupItemKey).forEach((type) => {
            // console.log(,'data[type]')
            series.push({
                name: `${data.name}:${type}`,
                type: 'line',
                smooth: true,
                lineStyle: {
                    color: data.color
                },
                yAxisIndex: index,
                symbolSize: 6,
                data: data[type],
                connectNulls: true 
            });
        });
        //设置y轴
        yData.push({
            boundaryGap: [0, '50%'],
            axisLine: {
                show: true,
                lineStyle: {
                    color: data.color,
                    }
            },
            axisTick:{
                show: true,
                inside: true
            },
            type: 'value',
            name: data.GroupName,
            position: index % 2 === 0 ? 'left' : 'right', // 根据 index 的奇偶性设置Y轴位置
            offset:  data.offset, //坐标轴距离
            splitLine: {
                show: true,
            },
        })
    });
    
    loadingByLinechart.value = false
    let aa = weatherData.value.map((item) => item.Time);
    seriesValByLinechart.xAxis = removeDuplicateDates(aa);
    seriesValByLinechart.seriesData = series;
    console.log(seriesValByLinechart.seriesData,'seriesData')
    seriesValByLinechart.yAxis = yData;
    seriesValByLinechart.legend = seriesValByLinechart.seriesData.map((item) => item.name);
    
}

function remoDataNull(data){
   // 使用 Map 去重并过滤掉值为 null 的数据
    let uniqueDataMap = new Map();
    data.forEach(([timestamp, value]) => {
        if (value !== null) {
            uniqueDataMap.set(timestamp, value);
        }
    });
    // 将 Map 转换回数组格式
    let uniqueData = Array.from(uniqueDataMap, ([timestamp, value]) => [timestamp, value]);
    return uniqueData
}
function removeDuplicateDates(dates) {
    // 使用 Set 来自动去除重复项
    const uniqueDates = new Set(dates);
    // 将 Set 转换回 Array
    return Array.from(uniqueDates);
}
//控制图表分组显示隐藏
function handleLineFilter(code) {
    loadingByLinechart.value = true
    code.isSelect = !code.isSelect;
    seriesValByLinechart.legendSelected = [];
    let legendData = seriesValByLinechart.legend;
    //选中的组
    let checkedArr = [] as any;
    lineChartArr.forEach((item) => {
        if(item.isSelect){
            checkedArr.push(item.title)
        }
    })
    // console.log(checkedArr)
    for (let item of legendData) {
        // 检查当前元素是否是 obj.title
        let strName = item.split(':')[0]
        if(checkedArr.includes(strName)){
            // 如果包含，则添加到 result 对象中，并设置值为 false
            selected[item] = false;
        }else{
            selected[item] = true;
        }
    }
    // console.log(selected)
    lineChartArr.forEach((item) => {
        if (item.title === code.title) {
            item.isSelect = code.isSelect;
        }
    });
    nextTick(()=>{
        loadingByLinechart.value = false
        seriesValByLinechart.legendSelected.push(selected);
        console.log(seriesValByLinechart.legendSelected);
    })
    
}
 // 动态生成颜色
 function generateRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

//获取图表数据
async function getGroupDetail() {
    loadingByLinechart.value = true
     //获取折线图数据
     let _GroupInfos = [] as any
    //  console.log(infoData.groupList)
    _GroupInfos = infoData.groupList.map(group => ({
        Name: group.name,
        AttributeList: group.attributeList.map(attr => attr.Key)
    }));
    try {
        let params = {
            StartTime: infoData.detailData.StartTime,
            EndTime: infoData.detailData.EndTime,
            GroupInfos: _GroupInfos
        }
        let res = await recorddiagnosis([params]);
        let arr = Array.isArray(res) ? res : [];
        lineChartArr = [];
        // 创建一个对象来存储每个GroupName的颜色
        const groupColors = {};
        // 遍历arr数组，为每个GroupName分配颜色
        const colorList = ['#FF9999','#FF33FF','#66CCFF','#66CCCC','#6699CC','#669900','#6666FF','#6633FF','#999966','#999900','#993399','#993333','#333300','#333366','#009900','#00FF66','#00FFFF','#CCFFFF','#CC0000','#330000'];
        let colorIndex = 0;
        arr.forEach(item => {
            if (!groupColors[item.GroupName]) {
                groupColors[item.GroupName] = colorList[colorIndex++ % colorList.length];
            }
            item.color = groupColors[item.GroupName];
        });

        // 将结果提取到lineChartArr中
        Object.keys(groupColors).forEach(groupName => {
            lineChartArr.push({
                color: groupColors[groupName],
                title: groupName,
                isSelect: false
            });
        });
        console.log(lineChartArr,'lineChartArr')
        weatherData.value = arr
        queryWeather()
    
    } catch (error) {
        queryWeather()
    }
}
//过滤已存在的属性
function filterTag(){
    let filteredTagList = []
    let _TagList= JSON.parse(JSON.stringify(infoData.detailData.TagList)) 
    console.log(infoData.groupList)
    console.log(_TagList)
    // 提取 list 中所有的 key
    let existingKeys = infoData.groupList.flatMap(item => item.attributeList).map(attr => attr.Key);
    // 过滤掉 _TagList 中已经存在的 key
    filteredTagList = _TagList.filter(tag => !existingKeys.includes(tag.Key));
    return filteredTagList
}
//添加分组
function addGroup(){
    let num = infoData.groupList.length + 1
    let obj = {
        name:'分组'+ num,
        attributeList:[]
    }
    infoData.groupList.push(obj)
    addAttribute(infoData.groupList.length-1)
}
//删除分组
function delgroup(index){
    infoData.groupList.splice(index,1)
    getGroupDetail()
}
//删除单个属性
function delAttribute(item,index){
    item.attributeList.splice(index,1)
    getGroupDetail()
}
//添加属性弹窗
function addAttribute(index){
    console.log(index)
    attributeForm.GroupName = infoData.groupList[index].name
    attributeForm.data = filterTag()
    selectIndex.value = index
    openModal()
}
//属性弹窗关闭
function handleUpdateAttribute(data){
    const {GroupName,checkedList} = data
    let _attributeList = infoData.groupList[selectIndex.value].attributeList;
    let matchedTags = infoData.detailData.TagList.filter(tag => checkedList.includes(tag.Key));
    let combinedTags = _attributeList.concat(matchedTags);
    infoData.groupList[selectIndex.value].attributeList = combinedTags;
    infoData.groupList[selectIndex.value].name = GroupName
    console.log(infoData.groupList)
    closeModal()
    getGroupDetail()
}
onMounted(async () => {
    getDiagnosticDetails()
    
})


</script>
<style scoped lang="less">
     .p-4-tag {
        padding: 8px;
        width: 100%;
        height: 100%;
        .tag {
            background-color: #fff;
            padding: 0 6px;
            padding-top: 5px;

            >.top{
                .container-ul{
                    display: flex;
                    flex-wrap: wrap; 
                    justify-content:flex-start;
                    color: #9E9E9E;
                }
                .container-ul>li{
                    min-width: 100px;
                    margin-right: 15px;
                    font-size: 13px;
                    padding-left: 20px;
                }
                .color-33{
                    color: #333;
                }
            }

            >.center{
                height: 620px;
                margin-top: 30px;
                // border: 1px solid;
            }

            >.bottom{
                min-height: 200px;
                margin-top: 10px;
                padding-bottom: 20px;
                .group-item-title{
                    position: relative;
                    height: 48px;
                    line-height: 45px;
                    border-bottom: 1px solid #C0C4CC;
                }
                .group-item-btn{
                    position: absolute;
                    right: 0;
                }
                .group-item-list{
                    display: flex;
                    flex-wrap: wrap;
                    margin-top: 10px;
                }
                .group-item-list>li{
                    width: 180px;
                    line-height: 30px;
                    border: 1px solid #3796EC;
                    border-radius: 3px;
                    color: #3f3f40;
                    font-size: 12px;
                    font-weight: 600;
                    margin-right: 15px;
                    padding-left: 8px;
                    position: relative;
                }
                .group-item-list>li:before{
                    content: "";
                    display: inline-block;
                    width: 6px;
                    height: 6px;
                    background-color: #9E9E9E;
                    border-radius: 50%;
                    margin-right: 3px;
                }
                .icon-eye{
                    position: relative;
                    top: 2px;
                    color: #646464;
                    cursor: pointer;
                }
                .icon-close{
                    position: absolute;
                    position: absolute;
                    right: 4px;
                    top: 9px;
                    cursor: pointer;
                }
            }
            .container-title{
                font-size: 14px;
                font-weight: 700;
                position: relative;
                padding-left: 8px
            }
            .container-title:before {
                content: "";
                background-color: #3796EC;
                width: 3px;
                height: 18px;
                position: absolute;
                left: 0;
                top: 50%;
                margin-top: -8px;
            }
        }
        .top-item {
            width: 100%;
            display: flex;
            justify-content: center;
            margin: 10px 0px 10px;
            .item {
                display: flex;
                margin: 0 10px;
                cursor: pointer;
            }
        }
        .item-chunk {
            height: 13px;
            width: 26px;
            margin-top: 3px;
            margin-right: 5px;
        }

    }
</style>